// 创建测试用户
require('dotenv').config({ path: '.env.local' });
const mysql = require('mysql2/promise');
const bcrypt = require('bcrypt');

async function createTestUser() {
  let connection;
  
  try {
    console.log('🔧 开始创建测试用户...\n');
    
    // 连接数据库
    connection = await mysql.createConnection({
      host: process.env.DB_HOST || 'localhost',
      port: parseInt(process.env.DB_PORT || '3306'),
      user: process.env.DB_USER || 'root',
      password: process.env.DB_PASSWORD,
      database: process.env.DB_NAME || 'math_academy',
    });
    
    console.log('✅ 数据库连接成功\n');
    
    const username = 'student01';
    const password = 'student123';
    const displayName = '学生01';
    
    // 检查用户是否已存在
    const [existing] = await connection.execute(
      'SELECT id FROM users WHERE username = ?',
      [username]
    );
    
    if (existing.length > 0) {
      console.log(`⚠️  用户 ${username} 已存在，先删除...`);
      await connection.execute('DELETE FROM users WHERE username = ?', [username]);
    }
    
    // 生成密码哈希
    const passwordHash = await bcrypt.hash(password, 10);
    
    // 插入新用户
    await connection.execute(
      `INSERT INTO users (username, password_hash, display_name, role, is_active) 
       VALUES (?, ?, ?, 'student', 1)`,
      [username, passwordHash, displayName]
    );
    
    console.log('✅ 测试用户创建成功！\n');
    console.log('═══════════════════════════════════════');
    console.log('📝 测试账号信息：');
    console.log('═══════════════════════════════════════');
    console.log(`用户名：${username}`);
    console.log(`密码：${password}`);
    console.log(`显示名称：${displayName}`);
    console.log(`角色：student`);
    console.log('═══════════════════════════════════════\n');
    console.log('💡 请用这个账号登录测试\n');
    
  } catch (error) {
    console.error('❌ 错误:', error.message);
  } finally {
    if (connection) {
      await connection.end();
    }
  }
}

createTestUser();

